package com.synnex.wmsdeployer.log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.synnex.wmsdeployer.DeployLog;

public class SimpleLogger {
	
	
	private static ThreadLocal<StringBuffer> threadLocal=new ThreadLocal<StringBuffer>();
	private static ThreadLocal<LoggerReceiver> loggerReceiver=new ThreadLocal<LoggerReceiver>();
	
	public static void setLoggerReceiver(LoggerReceiver lr){
		loggerReceiver.set(lr);
	}
	
	public static void clean(){
		StringBuffer sb=threadLocal.get();
		if(sb!=null){
			sb.delete(0,sb.length());
		}
	}
	
	public static void close(){
		threadLocal.set(null);
		loggerReceiver.set(null);
	}
	
	public static void addMessage(String str){
		StringBuffer sb=threadLocal.get();
		if(sb==null){
			sb=new StringBuffer();
			threadLocal.set(sb);
		}
		sb.append(str);
		
		LoggerReceiver lr=loggerReceiver.get();
		if(lr!=null){
			lr.pushMessage(str);
		}
	}
	
	public static String getMessage(){
		StringBuffer sb=threadLocal.get();
		if(sb==null)return null;
		return sb.toString();
		
	}
	public static boolean dumpToFile(DeployLog deployerLog){
		if(deployerLog==null||deployerLog.getDeployRecordFilePath()==null||deployerLog.getDeployLogFileName()==null){
			new RuntimeException("Deploy Record File Path and Deploy File Deploy Log File Name must be specific!");
		}
		StringBuffer sb=threadLocal.get();
		if(sb==null)return false;
		try {
			FileWriter fw=new FileWriter(new File(deployerLog.getDeployRecordFilePath()+File.separator+deployerLog.getDeployLogFileName()));
			fw.write(sb.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
